import React from 'react';
import { Spin } from 'antd';
import cookie from 'js-cookie';
import UploadOss from '@/components/UploadOss';

export default function ResumeUpload({
    previewUrl,
    children,
    onChange = () => {},
    onPreviewChange = () => {},
    ...rest
}) {
    const [uploading, setUploading] = React.useState(false);
    const [fileList, setFileList] = React.useState();

    if (!previewUrl) {
        return null;
    }

    const handleUpload = _res => {
        // 服务端实现兼容，暂不建议封装。
        fetch('/api/resource/oss/produceGetPreSignUrls', {
            body: JSON.stringify({
                sysCode: 'OA',
                fileList: _res
            }),
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                Authorization: cookie.get('Authorization')
            }
        })
            .then(response => response.json())
            .then(myJson => {
                const { data } = myJson;
                const { fileList: files = [] } = data || {};
                onPreviewChange(files[0]?.preUrl);
                setUploading(false);
            });
    };

    return (
        <Spin spinning={uploading}>
            <UploadOss
                uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                sysCode="OA"
                categoryCode="originalResumeFile"
                onUploaded={handleUpload}
                onChange={({ file = {} }) => {
                    if (file.status === 'uploading') {
                        setUploading(true);
                    }
                }}
                fileList={fileList}
                setFileList={(_fileList, uploadResourceResult) => {
                    setFileList(_fileList);
                    onChange(uploadResourceResult);
                }}
                checkFileSize={50}
                checkFileType="pdf、doc、xls、docx、wps"
                checkFileTypeMsg="只能上传 pdf、doc、xls、docx、wps 格式的文件！"
                checkFileSizeMsg="文件大小不能超过50MB！"
                showUploadList={false}
                showPreviewFile
                {...rest}
            >
                {children}
            </UploadOss>
        </Spin>
    );
}
